import { ApiCall } from 'tsrpc'
import { ReqGetConfigList, ResGetConfigList } from '../shared/api_config_editor/PtlGetConfigList'
import { ConfigListItem } from '../shared/api_config_editor/base'
import { configManager } from '../config/ConfigManager'

export default async function (call: ApiCall<ReqGetConfigList, ResGetConfigList>) {
    try {
        // 获取配置统计信息
        const stats = configManager.getStats()
        const skillStats = configManager.getSkillStats()
        
        // 构建配置列表
        const configList: ConfigListItem[] = [
            {
                type: 'equipment',
                name: '装备配置',
                description: '游戏装备模板配置，包括属性、技能等',
                count: stats.totalEquipments,
                lastModified: Date.now(),
                size: `${Math.round(stats.totalEquipments * 0.5)}KB`,
                status: stats.totalEquipments > 0 ? 'healthy' : 'warning'
            },
            {
                type: 'skill',
                name: '技能配置', 
                description: '游戏技能配置，包括效果、冷却等',
                count: skillStats.totalSkills,
                lastModified: Date.now(),
                size: `${Math.round(skillStats.totalSkills * 0.3)}KB`,
                status: skillStats.compatibilityScore > 80 ? 'healthy' : 'warning'
            }
        ]
        
        // 如果存在其他配置文件，也添加到列表中
        const fs = require('fs')
        const path = require('path')
        const configDir = path.resolve(__dirname, '../core/config')
        
        if (fs.existsSync(configDir)) {
            const files = fs.readdirSync(configDir)
            const jsonFiles = files.filter((file: string) => file.endsWith('.json'))
            
            for (const file of jsonFiles) {
                const fileName = file.replace('.json', '')
                const parts = fileName.split('_')
                
                if (parts.length >= 2) {
                    const type = parts[0]
                    const name = parts[1]
                    
                    // 避免重复添加已有的配置类型
                    if (!configList.find(item => item.type === type)) {
                        try {
                            const filePath = path.join(configDir, file)
                            const content = fs.readFileSync(filePath, 'utf-8')
                            const data = JSON.parse(content)
                            const count = Array.isArray(data) ? data.length : 1
                            const stats = fs.statSync(filePath)
                            
                            configList.push({
                                type,
                                name: name || type,
                                description: `${name || type}配置文件`,
                                count,
                                lastModified: stats.mtime.getTime(),
                                size: `${Math.round(stats.size / 1024)}KB`,
                                status: count > 0 ? 'healthy' : 'warning'
                            })
                        } catch (error) {
                            console.warn(`Failed to read config file ${file}:`, error)
                        }
                    }
                }
            }
        }
        
        call.succ({
            data: configList
        })
        
    } catch (error) {
        console.error('Failed to get config list:', error)
        call.error('获取配置列表失败', {
            errors: [(error as any).message]
        })
    }
}
